package com.itheima.mongodb.mapper;
import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.commons.pojo.Sound;
import com.itheima.interfaces.SoundApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;

import java.util.List;

@Service
public class SoundMapperImpl implements SoundApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void saveSound(Sound sound) {
        mongoTemplate.save(sound);
    }

    @Override
    public Sound receiveSound() {
        AggregationResults<Sound> aggregate = mongoTemplate.aggregate(Aggregation.newAggregation(Sound.class, Aggregation.sample(1)), Sound.class);
        List<Sound> mappedResults = aggregate.getMappedResults();
        Sound sound = mappedResults.get(0);
        return  sound;
    }
}
